declare @date_update nvarchar(100)= (select [DATE_UPDATE] from [DATE_EM_REPORT])
declare @date_last_month nvarchar(100)= convert (nvarchar(8),(SELECT DATEADD(m,2,CONVERT(date,@date_update)) ), 112) 
declare @date_end_month nvarchar(100)= (select [MAX_DATE_ENDMONTH] from [DATE_EM_REPORT])

exec('
IF EXISTS
(SELECT *
FROM tempdb.DBO.SYSOBJECTS O
WHERE o.xtype IN (''U'') AND 
o.name = ''##alert_deposit'')
DROP TABLE ##alert_deposit
SELECT * into ##alert_deposit
FROM SERVER74.BICDATA.DBO.DPTB_MASTER A
WHERE PRODUCT_NAME=''2. Term Deposit''
AND ((a.segment NOT IN(''KHCN'',''HH'') 
and a.branch_code not in (select branch_code from PhuongAnh.DBO.branchoff))
or (a.segment is null and LEFT(a.sector,1)>1))
AND MATDT BETWEEN '''+@date_update+''' AND '''+@date_last_month+'''

delete from TBL_ALERT_DEPOSIT_MATDT

insert TBL_ALERT_DEPOSIT_MATDT
SELECT CIF,CUSTOMER_NAME,ACCTNO,TERM,OPENNING_DATE,MATDT,BAL_QD,A.BRANCH_CODE,BRANCH_NAME_SME,      
ZONE_ID_SME AS REGION,A.DAO,C.DAO_NAME 
FROM ##ALERT_DEPOSIT A
LEFT JOIN SERVER74.BICDATA.DBO.BRANCH_CODE B
ON A.BRANCH_CODE=B.BRANCH_ID
LEFT JOIN TBL_HR C
ON A.DAO=C.DAO COLLATE DATABASE_DEFAULT
WHERE WITHDRAW_DATE IS NULL
')
select top 1 * from  SERVER74.BICDATA.DBO.DPTB_MASTER

--INSERT TBL_DATE_BUSINESS
--select convert(date,convert(nvarchar(10),[DATE_UPDATE]))  as date_data, 'TBL_ALERT_DEPOSIT_MATDT' from [DATE_EM_REPORT]


update b
set b.date_data = a.BUSINESS_DATE
from (select convert(date,convert(nvarchar(10),[DATE_UPDATE])) as business_date from [DATE_EM_REPORT]) a,  TBL_DATE_BUSINESS b
where b.name_table = 'TBL_ALERT_DEPOSIT_MATDT'
--select * from TBL_BRANCH

--select * from ##ALERT_DEPOSIT